#include "ets_sys.h"
#include "driver/uart.h"
#include "osapi.h"
#include "config.h"
#include "debug.h"
#include "gpio.h"
#include "user_interface.h"
#include "mem.h"
#include "user_config.h"


os_timer_t heartbeat_timer;
os_timer_t wifistate_timer;
uint8_t module_net_state = 0;


void heartbeat_callback(const void *arg);
void wifistate_callback(const void *arg);

void ICACHE_FLASH_ATTR
user_set_softap_config(void)
{
	struct softap_config config;
	os_memset(config.ssid, 0, 32);
	os_memset(config.password, 0, 64);
	wifi_softap_get_config(&config); // Get config first.
	os_memset(config.ssid, 0, 32);
	os_memset(config.password, 0, 64);

	os_memcpy(config.ssid, "esp8266", os_strlen("esp8266"));
	os_memcpy(config.password, "12345678", 8);
	config.authmode = AUTH_WPA_WPA2_PSK;
	config.ssid_len = 0;// or its actual length
	config.max_connection = 5; // how many stations can connect to ESP8266 softAP at most.
	wifi_softap_set_config(&config);// Set ESP8266 softap config .
}

void ICACHE_FLASH_ATTR
user_timer_heartbeat_init(void)
{
	os_timer_disarm(&heartbeat_timer);
	os_timer_setfn(&heartbeat_timer, (os_timer_func_t *)heartbeat_callback, NULL);
	os_timer_arm(&heartbeat_timer, 5000, 1);
}


void ICACHE_FLASH_ATTR
heartbeat_callback(const void *arg)
{
	heartbeat_send(sta_mac,module_net_state);
}

int ICACHE_FLASH_ATTR
str_replace_mac(char* raw_str,char* one ,char* two)
{
    char* p= NULL;
    p=os_strstr(raw_str,one);
	if(p)
	{
        os_printf("--------find symbol,os_strlen(two)=%d\n",os_strlen(two));
		os_memcpy(p,two,12);
		return 0;
	}
	return -1;
}

void ICACHE_FLASH_ATTR
user_timer_wifistate_init(void)
{
	os_timer_disarm(&wifistate_timer);
	os_timer_setfn(&wifistate_timer, (os_timer_func_t *)wifistate_callback, NULL);
	os_timer_arm(&wifistate_timer, 500, 1);
}

void ICACHE_FLASH_ATTR
wifistate_callback(const void *arg)
{
	static int toggle = 0,i=0;
	if(module_net_state == 0) WIFI_STATE_PIN_SET_HIGH();
	else if(module_net_state  == 1)
	{
		if(i++%10==0)
		{
			toggle = !toggle;
			if(toggle) WIFI_STATE_PIN_SET_LOW();
			else WIFI_STATE_PIN_SET_HIGH();
		}
	}
	else if(module_net_state  == 2) WIFI_STATE_PIN_SET_LOW();
	else if(module_net_state == 3)
	{
		toggle = !toggle;
		if(toggle) WIFI_STATE_PIN_SET_LOW();
		else WIFI_STATE_PIN_SET_HIGH();
	}
	else WIFI_STATE_PIN_SET_HIGH();
}


